<template>
    <div>
        <n-scrollbar style="max-height: 200px">
            <div class="params_main">
                <n-data-table
                :row-key="(row: RowData) => row.key"
                :columns="columns"
                :data="data"
                />
                <div class="add_btn_box">
                    <t-button @click="addRow" class="addData">+</t-button>
                </div>
            </div>
        </n-scrollbar>
        
    </div>
</template>

<script lang="ts" setup>
    import { watch, h, ref,defineComponent,PropType } from 'vue'
    // 表格

    // ========== 数据类型定义 ==========
    interface RowData {
    key: number
    KEY: string
    VALUE: string
    DESCRIPTION: string
    }

    interface Param {
    key: string
    value: string
    }

    const props=defineProps({
        paramsData:{
            type:Array as PropType<Param[]>
        }
    })

    // ========== 数据初始化 ==========
    const createData = (): RowData[] => {
    return [
        {
        key: Date.now(),
        KEY: '',
        VALUE: '',
        DESCRIPTION: ''
        }
    ]
    }



    let data = ref<RowData[]>(createData())

    // ========== 转换函数：将 Param[] → RowData[] ==========
    const convertToRowData = (params: Param[]): RowData[] => {
        return params.map((item, index) => ({
            key: Date.now() + index,
            KEY: item.key || '',
            VALUE: item.value || '',
            DESCRIPTION: ''
        }))
    }

    // ========== 监听外部数据变化 ==========
    watch(
    () => props.paramsData,
    (newVal) => {
        if (newVal && newVal.length > 0) {
        data.value = convertToRowData(newVal)
        } else {
        data.value = createData()
        }
    },
    { immediate: true, deep: true }
    )

    // watch(
    // () => data.value,
    // (newVal) => {
    //     // console.log('data 发生变化：', newVal)
    // },
    // { deep: true }  // ⬅️ 必须加 deep: true
    // )

    // ========== 根据 key 查找索引 ==========
    const getDataIndex = (key: number): number => {
    return data.value.findIndex(item => item.key === key)
    }


    const emit=defineEmits(['paramsKey','paramsValue'])

    // ========== 可编辑单元格组件：ShowOrEdit ==========
    // 必须用 defineComponent 才能使用 setup 和响应式
    const ShowOrEdit = defineComponent({
        props: {
            value: {
            type: String,
            default: ''
            },
            onUpdateValue: {
            type: Function,
            required: true
            },
            placeholder: {
            type: String,
            default: ''
            }
        },
        setup(props) {
            const isEdit = ref(false)
            const inputRef = ref<HTMLElement | null>(null)
            const inputValue = ref(props.value) 

            // 同步外部 value 变化
            watch(() => props.value, (newVal) => {
            inputValue.value = newVal
            })

            const handleInput = (e:any) => {
            // console.log('✅ handleInput 被调用了！新值：', inputValue.value)
            const value=e.target.value
            inputValue.value=value
            props.onUpdateValue(value)
            isEdit.value = false
            }

            return () =>
                h('input', {
                    ref: inputRef,
                    value: inputValue.value,
                    placeholder: props.placeholder,
                    // onInput: handleInput,
                    onChange: handleInput,
                    onBlur: handleInput,
                    onClick: (e: MouseEvent) => e.stopPropagation(), // 防止冒泡
                    style:'border: none !important;',
                    class:"none-border-input",
                    })
        }
    })

    // ========== 列配置 ==========
    const columns = [
        {
            title: 'KEY',
            key: 'KEY',
            width: 300,
            render(row: RowData) {
            const index = getDataIndex(row.key)
            return h(ShowOrEdit, {
                value: row.KEY,
                onUpdateValue: (v: string) => {
                    // console.log('输入key:',v);
                    // const newRow = { ...data.value[index], KEY: v }
                    // data.value[index] = newRow
                    data.value[index].KEY=v
                    emit('paramsKey',v)
                    
                },
                placeholder: 'Key'
            })
            }
        },
        {
            title: 'VALUE',
            key: 'VALUE',
            width: 300,
            render(row: RowData) {
            const index = getDataIndex(row.key)
            return h(ShowOrEdit, {
                value: row.VALUE,
                onUpdateValue: (v: string) => {
                // const newRow = { ...data.value[index], VALUE: v }
                // data.value[index] = newRow
                data.value[index].VALUE=v
                emit('paramsValue',v)
                
                },
                placeholder: 'Value'
            })
            }
        },
        {
            title: 'DESCRIPTION',
            key: 'DESCRIPTION',
            render(row: RowData) {
            const index = getDataIndex(row.key)
            return h(ShowOrEdit, {
                value: row.DESCRIPTION,
                onUpdateValue: (v: string) => {
                // console.log('输入description:',v);
                const newRow = { ...data.value[index], DESCRIPTION: v }
                data.value[index] = newRow
                },
                placeholder: 'Description'
            })
            }
        }
    ]

    //表格加一行
    function addRow(){
        data.value.push({
            key: Date.now(), // 唯一 key
            KEY: '',
            VALUE: '',
            DESCRIPTION: ''
        })
    }
    

</script>

<style scoped>
    .addData {
        background-color: #0052d9;
        color: #fff;
        border: 0px;
    }
    .add_btn_box {
        display: flex;
        margin-top: 10px;
    }
    .addData:hover {
        background-color: #0047ba;
    }
    :deep(.n-data-table-td),
    :deep(.n-data-table-th) {
        border-right: 1px solid #e8e8e8
    }
    :deep(.n-data-table-td:last-child),
    :deep(.n-data-table-th:last-child) {
        border-right: none;
    }
    :deep(.none-border-input:hover) {
        /* background-color: rgba(247, 247, 250, 1); */
        background-color: #fff;
    }
    .params_main {
        height: 260px;
    }
   
</style>